<?php
class BotDetails {
	function getAgent() {
		return "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
	}
	
	function getOFFReffer() {
		return "http://ourfooty.com.au/forum/index.php";
	}
	
	function getSCReffer() {
		return "http://supercoach.heraldsun.com.au";
	}	
	
	function getCookiePath() {
		return "cookies.txt";
	}
	
}

function forumLogin($ch) {
	$user_id = "MasoCoachBot";
	$user_password = "toBhcaoCosaM";
	
	$LOGINURL = "http://ourfooty.com.au/forum/member.php";
    curl_setopt($ch, CURLOPT_URL,$LOGINURL);
	$ch = getCommonDetails($ch, "OFF");
    curl_close ($ch);

	$LOGINURL = "http://ourfooty.com.au/forum/member.php";
	$data = array('username' => $user_id, 'password' => $user_password, 'action' => 'do_login', 'url' => '');
	$ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$LOGINURL);
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    
    return $ch;
}

function forumLogout($ch) {
    curl_setopt($ch, CURLOPT_URL,"http://ourfooty.com.au/forum/index.php");
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "logoutkey=") + 10;
    $logoutkey = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $url = "http://ourfooty.com.au/forum/member.php?action=logout&logoutkey=" . $logoutkey;
    curl_setopt($ch, CURLOPT_URL,$url);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    
    return $ch;
}

function updateForum() {
	$ch = curl_init();
	$ch = forumLogin($ch);
	$ch = updatePicks($ch);
	
	curl_close($ch);
}	
	
function updatePicks($ch, $message, $settings) {	
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/showthread.php?tid=" . $settings->picksPageID);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "my_post_key\" value=\"") + 20;
    $my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "posthash\" value=\"") + 17;
    $posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "lastpid\" value=\"") + 16;
    $lastPid = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "from_page\" value=\"") + 18;
    $fromPage = substr($result, $start, (strpos($result, "\"", $start) - $start));    
    
    $data = array('my_post_key' => $my_post_key, 'subject' => 'RE: Draft Picks', 'action' => 'do_newreply', 'posthash' => $posthash, 'lastpid' => $lastPid, 'from_page' => $fromPage, 'tid' => $settings->picksPageID, 'method' => 'quickreply', 'message' => $message);
    
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newreply.php?tid=" . $settings->picksPageID . "&amp;processed=1");
	$ch = getCommonDetails($ch, "OFF");
	
	$result = curl_exec ($ch);    
	
    return $ch;
}

function updateTrades($ch, $message, $settings) {	
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/showthread.php?tid=" . $settings->tradesPageID);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "my_post_key\" value=\"") + 20;
    $my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "posthash\" value=\"") + 17;
    $posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "lastpid\" value=\"") + 16;
    $lastPid = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "from_page\" value=\"") + 18;
    $fromPage = substr($result, $start, (strpos($result, "\"", $start) - $start));    
    
    $data = array('my_post_key' => $my_post_key, 'subject' => 'RE: Trades', 'action' => 'do_newreply', 'posthash' => $posthash, 'lastpid' => $lastPid, 'from_page' => $fromPage, 'tid' => $settings->tradesPageID, 'method' => 'quickreply', 'message' => $message);
    
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newreply.php?tid=" . $settings->tradesPageID . "&amp;processed=1");
	$ch = getCommonDetails($ch, "OFF");
	
	$result = curl_exec ($ch);    
	
    return $ch;
}

function updateTeamsSubmitted($ch, $message, $settings) {
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/showthread.php?tid=" . $settings->submittedTeamsPageID);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "my_post_key\" value=\"") + 20;
    $my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "posthash\" value=\"") + 17;
    $posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "lastpid\" value=\"") + 16;
    $lastPid = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "from_page\" value=\"") + 18;
    $fromPage = substr($result, $start, (strpos($result, "\"", $start) - $start));    
    
    $data = array('my_post_key' => $my_post_key, 'subject' => 'RE: Round ' . getCurrentRound() . ' Teams', 'action' => 'do_newreply', 'posthash' => $posthash, 'lastpid' => $lastPid, 'from_page' => $fromPage, 'tid' => $settings->submittedTeamsPageID, 'method' => 'quickreply', 'message' => $message);
    
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newreply.php?tid=" . $settings->submittedTeamsPageID . "&amp;processed=1");
	$ch = getCommonDetails($ch, "OFF");
	
	$result = curl_exec ($ch);    
	
    return $ch;
}

function createTeamsThread($ch, $league, &$topicId, $settings) {
	$round = getCurrentRound();
	$message = "[iframe=800x850b1]http://ourfooty.com.au/masoCoach/phpMain/pages/home/displayForForum.php?type=selectedTeamsForWeek&leagueId=" . $league . "&round=" . $round . "[/iframe]";
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newthread.php?fid=" . $settings->forumID);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "my_post_key\" value=\"") + 20;
    $my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "posthash\" value=\"") + 17;
    $posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
    
    $data = array('my_post_key' => $my_post_key, 'subject' => 'Round ' . $round . ' Teams', 'action' => 'do_newthread', 'posthash' => $posthash, 'message' => $message, 'attachmentaid' => '', 'attachmentact' => '', 'quoted_ids' => '', 'tid' => '');
    
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newthread.php?fid=" . $settings->forumID . "&amp;processed=1");
	$ch = getCommonDetails($ch, "OFF");
	
	$result = curl_exec ($ch);
	
	$start = strpos($result, "tid=") + 4;
	$topicId = substr($result, $start, (strpos($result, "\"", $start) - $start));
	
    return $ch;	
}

function createResultsThread($ch, $league, &$topicId, $settings) {
	$round = getCurrentRound();
	$message = "[iframe=800x850b1]http://ourfooty.com.au/masoCoach/phpMain/pages/home/displayForForum.php?type=results&leagueId=" . $league . "&round=" . $round . "[/iframe]";
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newthread.php?fid=" . $settings->forumID);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "my_post_key\" value=\"") + 20;
    $my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "posthash\" value=\"") + 17;
    $posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
    
    $data = array('my_post_key' => $my_post_key, 'subject' => 'Round ' . $round . ' Results', 'action' => 'do_newthread', 'posthash' => $posthash, 'message' => $message, 'attachmentaid' => '', 'attachmentact' => '', 'quoted_ids' => '', 'tid' => '');
    
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newthread.php?fid=" . $settings->forumID . "&amp;processed=1");
	$ch = getCommonDetails($ch, "OFF");
	
	$result = curl_exec ($ch);
	
	$start = strpos($result, "tid=") + 4;
	$topicId = substr($result, $start, (strpos($result, "\"", $start) - $start));
	
    return $ch;	
}

function updateResults($ch, $message, $settings) {	
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/showthread.php?tid=" . $settings->resultsPageID);
	$ch = getCommonDetails($ch, "OFF");
    $result = curl_exec ($ch);
    $start = strpos($result, "my_post_key\" value=\"") + 20;
    $my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "posthash\" value=\"") + 17;
    $posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "lastpid\" value=\"") + 16;
    $lastPid = substr($result, $start, (strpos($result, "\"", $start) - $start));
    $start = strpos($result, "from_page\" value=\"") + 18;
    $fromPage = substr($result, $start, (strpos($result, "\"", $start) - $start));    
    
    $data = array('my_post_key' => $my_post_key, 'subject' => 'RE: Round ' . getCurrentRound() . ' Results', 'action' => 'do_newreply', 'posthash' => $posthash, 'lastpid' => $lastPid, 'from_page' => $fromPage, 'tid' => $settings->resultsPageID, 'method' => 'quickreply', 'message' => $message);
    
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newreply.php?tid=" . $settings->resultsPageID . "&amp;processed=1");
	$ch = getCommonDetails($ch, "OFF");
	
	$result = curl_exec ($ch);    
	
    return $ch;
}

function getCommonDetails($ch, $site) {
	curl_setopt($ch, CURLOPT_USERAGENT, BotDetails::getAgent());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	if ($site == "OFF") {
		curl_setopt($ch, CURLOPT_REFERER, BotDetails::getOFFReffer());
	}
	else {
		curl_setopt($ch, CURLOPT_REFERER, BotDetails::getSCReffer());		
	}
	curl_setopt($ch, CURLOPT_COOKIEFILE, BotDetails::getCookiePath());
	curl_setopt($ch, CURLOPT_COOKIEJAR, BotDetails::getCookiePath());
	
	return $ch;
}

function scSiteLogin($ch) {
	$user_id = "cjmason8@gmail.com";
	$user_password = "jade76";
	
	$LOGINURL = "http://supercoach.heraldsun.com.au/?p=index";
    	curl_setopt($ch, CURLOPT_URL,$LOGINURL);
	$ch = getCommonDetails($ch, "SC");
    	curl_close ($ch);

	$LOGINURL = "http://supercoach.heraldsun.com.au/?p=index";
	$data = array('email' => $user_id, 'password' => $user_password, 'login_request' => 'true');
	$ch = curl_init(); 
    	curl_setopt($ch, CURLOPT_URL,$LOGINURL);
    	curl_setopt($ch, CURLOPT_POST, 1); 
    	curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	$ch = getCommonDetails($ch, "SC");
    	$result = curl_exec ($ch);
    	if (strpos($result, "<p class=\"value-small bad\">OPEN</p>") != "") {
    		curl_close ($ch);
       		return null;
   	 }
    
   	 return $ch;
}

function sendTeamReminders($leagues) {
	$ch = curl_init();
	$ch = forumLogin($ch);	
	foreach ($leagues as $league) {
    	$message = getTeamReminders($league); 
        if ($message != null && $message != "") {
			$settings = getSystemSettings($league);
			curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/showthread.php?tid=" . $settings->submittedTeamsPageID);
			$ch = getCommonDetails($ch, "OFF");
			$result = curl_exec ($ch);
			$start = strpos($result, "my_post_key\" value=\"") + 20;
			$my_post_key = substr($result, $start, (strpos($result, "\"", $start) - $start));
			$start = strpos($result, "posthash\" value=\"") + 17;
			$posthash = substr($result, $start, (strpos($result, "\"", $start) - $start));
			$start = strpos($result, "lastpid\" value=\"") + 16;
			$lastPid = substr($result, $start, (strpos($result, "\"", $start) - $start));
			$start = strpos($result, "from_page\" value=\"") + 18;
			$fromPage = substr($result, $start, (strpos($result, "\"", $start) - $start));    
	
			$data = array('my_post_key' => $my_post_key, 'subject' => 'RE: Trades', 'action' => 'do_newreply', 'posthash' => $posthash, 'lastpid' => $lastPid, 'from_page' => $fromPage, 'tid' => $settings->submittedTeamsPageID, 'method' => 'quickreply', 'message' => $message);
	
			curl_setopt($ch, CURLOPT_POST, 1); 
			curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
			curl_setopt($ch, CURLOPT_URL, "http://ourfooty.com.au/forum/newreply.php?tid=" . $settings->submittedTeamsPageID . "&amp;processed=1");
			$ch = getCommonDetails($ch, "OFF");
	
			curl_exec ($ch);
        }
	}
	
	$ch = forumLogout($ch);
	curl_close ($ch);
}

function getTeamReminders($leagueId) {
	$teams = retrieveCoachesNotSubmittedTeams($leagueId);
	$invalidTeams = getInvalidTeams($leagueId);
	
	$result = "";
	if ($teams != null && count($teams) > 0) {
		$result = "[b]The following coaches are yet to submit their teams:[/b]\n";
		foreach ($teams as $team) {
			$result .= "@[" . $team . "]\n\n";
		}
	}
	if ($invalidTeams != null && count($invalidTeams) > 0) {	
		$result .= "[b]The following coaches have invalid players in their teams:[/b]\n";
		foreach ($invalidTeams as $invalidTeam) {
			$result .= "@[" . $invalidTeam->coachName . "]\n";
			$isFirst = true;
			foreach ($invalidTeam->invalidPlayers as $invalidPlayer) {			
				if (!$isFirst) {
					$result .= ", ";
				}
				else {
					$isFirst = false;
				}
				
				$result .= getPlayerDisplayForForum($invalidPlayer);
			}
			$result .= "\n";
		}
	}	
	
	return $result;
}

function processSelectedTeams($hours, $bypass) {
	if (needToGetSelectedTeams($hours) || $bypass) {
		$result = getAFLWebsiteSource();
		$count = 0;
		while (strpos($result, "Followers") != "" && $count < 3) {
			$result = getAFLWebsiteSource();
		}
   		parseSelectedTeams($result);
   		updateExtendedBench();
        informAFLTeamsUploaded(getActiveLeagues());
	}
}

function getAFLWebsiteSource() {
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL,"http://www.afl.com.au/teams/tabid/16469/default.aspx?templateToDisplay=text");
	$ch = getCommonDetails($ch, "SC");
	$result = curl_exec ($ch);
	curl_close($ch);
	
	return $result;
}

function getScores($hours, $bypass) {
	$uploadedSomething = false;
	if (isTimeToCheckScores($hours) || $bypass) {
		$ch = curl_init();
		$ch = scSiteLogin($ch);
        if ($ch != null) {
  	  		curl_setopt($ch, CURLOPT_URL, "http://supercoach.heraldsun.com.au/?p=livestats&m=load_live_stats&tab=2&chart=true&chart_pressed=true&noanimation=true");
		   	$ch = getCommonDetails($ch, "SC");
		   	$result = curl_exec($ch);
		
		   	$uploadedSomething = parseScores($result);
		   	
		   	curl_close($ch);
		}
		
		updateTimeToPerformTask(TimeToPerformTaskType::ScoreCheck);
        createDisplayRound(getCurrentRound());
        createFixture();
	}
	
	return $uploadedSomething;
}

function expirePicks($leagues) {
	foreach ($leagues as $league) {
		$settings = getSystemSettings($league);	
		skipPicks($league, $settings);
		$results = getMadeAndSkippedPicks($league);
		$picksString = "";
		$count = count($results);
		if ($count > 0) {
			$picksString .= "[list]";
			for ($i = 0; $i < $count; $i++) {
				if ($results[$i]->state == 'PICKED') {
					$picksString .= "[*] Pick #" . $results[$i]->pickNumber . " - " . $results[$i]->coachName . " picks " . getPlayerDisplayForForum($results[$i]->player);   
			
				}
				if ($results[$i]->state == 'SKIPPED') {
					$picksString .= "[*] " . $results[$i]->coachName . " was SKIPPED for Pick #" . $results[$i]->pickNumber;
				}
			}
			$picksString .= "[/list]";
			$currentPickUser = getCurrentPickUser($league);
		    if ($currentPickUser != "") {
		       $picksString .= "@[" . $currentPickUser . "]'s pick";
		    }
		}
		
		if ($picksString != "" && $settings->bot == "ON") {
			$ch = curl_init();
			$ch = forumLogin($ch);
			updateDraftToInformed($league);
			
			$ch = updatePicks($ch, $picksString, $settings);
			
			$ch = forumLogout($ch);
			curl_close($ch);
			
			sleep(20);			
		}
	}
}

function informTrades($leagues) {
	foreach ($leagues as $league) {
		$settings = getSystemSettings($league);	
		$madeTrades = getMadeTrades($league);
		$countTrades = count($madeTrades);
		$tradesString = "";
		if ($countTrades > 0) {
			for ($j = 0; $j < $countTrades; $j++) {
				$tradesString .= getTradeStringForForum($madeTrades[$j]);   
			}
		}
		
		if ($tradesString != "" && $settings->bot == "ON") {
			$ch = curl_init();
			$ch = forumLogin($ch);
			updateTradeToInformed($league);
	   	 	$ch = updateTrades($ch, $tradesString, $settings);
	   	 	
	   	 	$ch = forumLogout($ch);
			curl_close($ch);
			
			sleep(20);			
		}
	}
}

function informLtiDelist($leagues) {
	foreach ($leagues as $league) {
		$settings = getSystemSettings($league);	
		$ltiDelistings = getLtiSpud($league);
		$countLtiDelistings = count($ltiDelistings);
		
		$tradesString = "";
		if ($countLtiDelistings > 0) {
			$tradesString .= "[list]";
			for ($j = 0; $j < $countLtiDelistings; $j++) {
				$tradesString .= "[*] " . getLtiStringForForum($ltiDelistings[$j]);   
			}
			$tradesString .= "[/list]";
		}
		
		if ($tradesString != "" && $settings->bot == "ON") {
			$ch = curl_init();
			$ch = forumLogin($ch);		
			updateLtiDelistToInformed($league);
			$ch = updateTrades($ch, $tradesString, $settings);
			
	   	 	$ch = forumLogout($ch);
			curl_close($ch);
			
			sleep(20);			
		}
	}
}

function informTeamsSubmitted($leagues) {
	foreach ($leagues as $league) {
		$settings = getSystemSettings($league);
		$teamsSubmitted = "";
		$selectedTeams = getSelectedTeamsForWeek($league, true, getCurrentRound());
		$countSelectedTeams = count($selectedTeams);
		if ($countSelectedTeams > 0) {
			for ($i = 0; $i < $countSelectedTeams; $i++) {
				$teamsSubmitted .= getTeamDisplayForForum($selectedTeams[$i]);
			}
		}
		
		if ($teamsSubmitted != "" && $settings->bot == "ON") {
			$ch = curl_init();
			$ch = forumLogin($ch);
			if ($settings->submittedTeamsPageID == "1") {
				$topicId = "1";
				$ch = createTeamsThread($ch, $league, $topicId, $settings);
				updateSubmittedTeamsPageID($topicId, $league);
				$settings->submittedTeamsPageID = $topicId;
			}
	   	   	$ch = updateTeamsSubmitted($ch, $teamsSubmitted, $settings);
	   	   	updateTeamsSubmittedStatus($league);
	   	   	
	   	 	$ch = forumLogout($ch);
			curl_close($ch);   	   	
		}
	}
}

function informAFLTeamsUploaded($leagues) {
	$ch = curl_init();
	$ch = forumLogin($ch);
	foreach ($leagues as $league) {
		$settings = getSystemSettings($league);
		if ($settings->bot == "ON") {
	   	   	$ch = updateTeamsSubmitted($ch, "AFL Teams have now been uploaded, indicators should now show valid players.", $settings);
			sleep(20);
		}
	}
 	$ch = forumLogout($ch);
	curl_close($ch);	
}

function informResultsUpdated($leagues) {
	$ch = curl_init();
	$ch = forumLogin($ch);
	foreach ($leagues as $league) {
		$settings = getSystemSettings($league);	
		$currentRoundStatus = getCurrentRoundStatus();
		if ($settings->bot == "ON") {
			$message = "Scores have been updated";
			if (getNumberOfTeamsSubmitted(getCurrentRound()) == 18) {
				$message .= " the round has been finalised and the ladder updated.";	
			}
			if ($settings->resultsPageID == "1") {
				$topicId = "1";
				$ch = createResultsThread($ch, $league, $topicId, $settings);
				updateResultsPageID($topicId, $league);
				$settings->resultsPageID = $topicId;
			}	
	   	   	$ch = updateResults($ch, $message, $settings);
		}
	}
 	$ch = forumLogout($ch);
	curl_close($ch);	
}

function isTimeToCheckScores($hours) {
	$timeToPerformTask = getTimeToPerformTask(TimeToPerformTaskType::ScoreCheck);
	if ($timeToPerformTask != null) {
		$now = strtotime("+" . $hours . " hours");
		$dateComponents = getdate($now);
		if ($dateComponents["wday"] == $timeToPerformTask->day && $dateComponents["hours"] == $timeToPerformTask->hours && $dateComponents["minutes"] >= $timeToPerformTask->minutes) {
			return true;
		}
	}
	
	return false;
}
?>